import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:developer' as developer;
import '../../services/file_service.dart';
import 'preview_utils.dart';

/// 视频预览组件
/// 用于显示视频类型文件的预览
class VideoPreview extends StatefulWidget {
  final String? previewUrl;
  final String? fileName;
  final VoidCallback? onRetry;

  const VideoPreview({
    Key? key,
    required this.previewUrl,
    this.fileName,
    this.onRetry,
  }) : super(key: key);

  @override
  State<VideoPreview> createState() => _VideoPreviewState();
}

class _VideoPreviewState extends State<VideoPreview> {
  VideoPlayerController? _videoController;
  ChewieController? _chewieController;
  bool _isLoading = true;
  String? _error;
  bool _isFullScreen = false;
  Duration _currentPosition = Duration.zero;
  Duration _totalDuration = Duration.zero;
  double _bufferingProgress = 0.0;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  @override
  void dispose() {
    _videoController?.dispose();
    _chewieController?.dispose();
    super.dispose();
  }

  /// 初始化视频播放器
  Future<void> _initializeVideo() async {
    if (widget.previewUrl == null) {
      setState(() {
        _error = '无效的视频地址';
        _isLoading = false;
      });
      return;
    }

    try {
      developer.log('尝试加载视频: ${widget.previewUrl}', name: 'VideoPreview');

      // 初始化视频控制器
      _videoController = VideoPlayerController.networkUrl(
        Uri.parse(widget.previewUrl!),
        videoPlayerOptions: VideoPlayerOptions(
          mixWithOthers: true,
          allowBackgroundPlayback: false,
        ),
        httpHeaders: {
          'User-Agent':
              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          'Accept': 'video/mp4,video/webm,video/*,*/*',
          'Accept-Encoding': 'gzip, deflate, br',
          'Range': 'bytes=0-',
        },
      );

      // 等待初始化完成
      await _videoController!.initialize();

      // 获取视频信息
      final videoSize = _videoController!.value.size;
      final videoRatio = _videoController!.value.aspectRatio;
      final isPortrait = videoRatio < 1.0;

      developer.log(
        '视频信息:\n'
        '宽度: ${videoSize.width}\n'
        '高度: ${videoSize.height}\n'
        '宽高比: $videoRatio\n'
        '是否竖屏: $isPortrait',
        name: 'VideoPreview',
      );

      // 创建Chewie控制器
      _chewieController = ChewieController(
        videoPlayerController: _videoController!,
        autoPlay: false,
        looping: false,
        deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
        deviceOrientationsOnEnterFullScreen:
            isPortrait
                ? [DeviceOrientation.portraitUp]
                : [
                  DeviceOrientation.landscapeLeft,
                  DeviceOrientation.landscapeRight,
                ],
        aspectRatio: videoRatio,
        allowFullScreen: true,
        allowMuting: true,
        showControls: true,
        allowPlaybackSpeedChanging: true,
        playbackSpeeds: const [0.5, 0.75, 1, 1.25, 1.5, 2],
        placeholder: _buildPlaceholder(),
        materialProgressColors: ChewieProgressColors(
          playedColor: Theme.of(context).primaryColor,
          handleColor: Theme.of(context).primaryColor,
          backgroundColor: Colors.grey[300]!,
          bufferedColor: Theme.of(context).primaryColor.withOpacity(0.5),
        ),
        errorBuilder: (context, errorMessage) {
          return _buildErrorWidget(errorMessage);
        },
      );

      // 监听全屏状态变化
      _chewieController!.addListener(() {
        final isFullScreen = _chewieController!.isFullScreen;
        developer.log(
          '全屏状态变化:\n'
          '是否全屏: $isFullScreen\n'
          '视频比例: $videoRatio\n'
          '是否竖屏: $isPortrait',
          name: 'VideoPreview',
        );

        if (mounted) {
          setState(() {
            _isFullScreen = isFullScreen;
          });
        }
      });

      // 监听视频状态
      _videoController!.addListener(_onVideoControllerUpdate);

      if (mounted) {
        setState(() {
          _isLoading = false;
          _totalDuration = _videoController!.value.duration;
        });
      }

      developer.log('视频初始化成功', name: 'VideoPreview');
    } catch (e) {
      developer.log('视频初始化错误: $e', name: 'VideoPreview');
      _handleVideoError('视频初始化失败: ${e.toString()}');
    }
  }

  /// 视频控制器更新回调
  void _onVideoControllerUpdate() {
    if (!mounted || _videoController == null) return;

    setState(() {
      _currentPosition = _videoController!.value.position;
      _bufferingProgress =
          _videoController!.value.buffered.isNotEmpty
              ? _videoController!.value.buffered.last.end.inMilliseconds /
                  _videoController!.value.duration.inMilliseconds
              : 0.0;
    });
  }

  /// 处理视频错误
  void _handleVideoError(String message) {
    if (mounted) {
      setState(() {
        _error = message;
        _isLoading = false;
      });
    }
    _chewieController?.dispose();
    _videoController?.dispose();
    _chewieController = null;
    _videoController = null;
  }

  /// 构建占位符
  Widget _buildPlaceholder() {
    return Container(
      color: Colors.black87,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.play_circle_outline,
              color: Colors.white.withOpacity(0.8),
              size: 84,
            ),
            const SizedBox(height: 16),
            if (widget.fileName != null)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Text(
                  widget.fileName!,
                  style: const TextStyle(color: Colors.white70),
                  textAlign: TextAlign.center,
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建错误界面
  Widget _buildErrorWidget(String message) {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, color: Colors.red[300], size: 64),
            const SizedBox(height: 16),
            Text(
              '视频加载失败',
              style: TextStyle(
                color: Colors.red[300],
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              message,
              textAlign: TextAlign.center,
              style: const TextStyle(color: Colors.grey),
            ),
            const SizedBox(height: 24),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton.icon(
                  onPressed: () {
                    setState(() {
                      _error = null;
                      _isLoading = true;
                    });
                    _initializeVideo();
                  },
                  icon: const Icon(Icons.refresh),
                  label: const Text('重试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Theme.of(context).primaryColor,
                    foregroundColor: Colors.white,
                  ),
                ),
                const SizedBox(width: 16),
                if (widget.previewUrl != null)
                  OutlinedButton.icon(
                    onPressed: () async {
                      final url = Uri.parse(widget.previewUrl!);
                      if (await canLaunchUrl(url)) {
                        await launchUrl(
                          url,
                          mode: LaunchMode.externalApplication,
                        );
                      }
                    },
                    icon: const Icon(Icons.download),
                    label: const Text('下载视频'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建加载界面
  Widget _buildLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('视频加载中...'),
          SizedBox(height: 8),
          Text(
            '首次加载可能需要较长时间',
            style: TextStyle(color: Colors.grey, fontSize: 12),
          ),
        ],
      ),
    );
  }

  /// 构建视频信息栏
  Widget _buildVideoInfoBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.fileName != null) ...[
            Text(
              widget.fileName!,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
          ],
          Row(
            children: [
              Text(
                '时长: ${PreviewUtils.formatDuration(_totalDuration)}',
                style: const TextStyle(color: Colors.grey),
              ),
              const SizedBox(width: 16),
              if (_bufferingProgress > 0)
                Text(
                  '已缓冲: ${(_bufferingProgress * 100).toStringAsFixed(1)}%',
                  style: const TextStyle(color: Colors.grey),
                ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_error != null) {
      return _buildErrorWidget(_error!);
    }

    if (_isLoading) {
      return _buildLoadingWidget();
    }

    if (_videoController == null || _chewieController == null) {
      return const Center(child: Text('无法加载视频'));
    }

    final screenSize = MediaQuery.of(context).size;
    final videoSize = _videoController!.value.size;
    final videoRatio = _videoController!.value.aspectRatio;
    final isPortrait = videoRatio < 1.0;

    developer.log(
      '构建视频播放器:\n'
      '屏幕尺寸: ${screenSize.width}x${screenSize.height}\n'
      '视频尺寸: ${videoSize.width}x${videoSize.height}\n'
      '视频比例: $videoRatio\n'
      '是否竖屏: $isPortrait\n'
      '是否全屏: $_isFullScreen',
      name: 'VideoPreview',
    );

    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Container(
                  width: isPortrait ? screenSize.width : null,
                  child: AspectRatio(
                    aspectRatio: videoRatio,
                    child: Chewie(controller: _chewieController!),
                  ),
                ),
              ),
            ),
            if (!_isFullScreen) _buildVideoInfoBar(),
          ],
        ),
      ),
    );
  }
}
